<?php

namespace app\api\service;

use app\store\model\Order;
use think\facade\Db;

class OrderService
{

    /**
     * 是否符合购买商品生日赠送积分
     */
    public static function giveBirthdayPoint($user_id)
    {
        $u_info = Db::name('user')->where('user_id', $user_id)->find();
        $user_grade_id = $u_info['user_grade_id']; //用户等级id
        $birthday = $u_info['birthday']; //用户生日
        if ($birthday && date('Y-m-d') == $birthday && $user_grade_id) {
            $grade_info = UserGradeService::findOne($user_grade_id);

            if (!empty($grade_info)) {
                $birthday_give_integral = $grade_info['birthday_give_integral']; //生日赠送积分倍数
                return $birthday_give_integral;
            }

        }
        return 0;
    }

    /**
     * 获取自提点
     */
    public static function findAllPickPoint($lat, $lng, $store_id)
    {
        $list = Db::name('pick_point')->field("*,(6378.138 * 2 * asin(sqrt(pow(sin((lat * pi() / 180 - " . $lat . " * pi() / 180) / 2),2) + cos(lat * pi() / 180) * cos(" . $lat . " * pi() / 180) * pow(sin((lng * pi() / 180 - " . $lng . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->where(['status' => 1, 'delete_time' => 0, 'store_id' => $store_id])
            ->order('distance')
            ->paginate(10)->each(function ($item) {
            $item['distance'] = bcdiv($item['distance'], 1000, 2);
            $item['distance_unit'] = 'km';
            return $item;
        });
        return $list;
    }

    /**
     * 获取订单列表
     * */
    public static function getOrderList($uid, $param)
    {

        $query = Order::field('id,order_type,order_no,discount_amount,real_amount,redeem_integral,status')
            ->where('user_id', $uid)
            ->with('items');

        if (!empty($param['order_status'])) {
            $query->where('status', $param['order_status']);
        }

        if (!empty($param['order_type'])) {
            $query->where('order_type', $param['order_type']);
        }

        $orders = $query->paginate(10);

        return $orders;
    }

    /**
     *
     * 获取用户等级
     * */
    public static function findUserGrade($user_id)
    {
        $user_trade_id = Db::name('user')->where('user_id', $user_id)->value('user_grade_id');

        return $user_trade_id;
    }

    /**
     * 获取商品优惠券
     * */

    public static function getCouponDiscountAmount($user_id, $coupon_id, $goods_id, $total_amount)
    {
        $coupon = Db::name('user_coupon')
            ->alias('a')
            ->field('a.id,a.coupon_type,a.with_amount,a.used_amount,a.end_time')
            ->join('coupon b', 'a.coupon_id=b.id')
            ->join('coupon_goods c', 'a.coupon_id=c.coupon_id')
            ->where(['a.user_id' => $user_id, 'a.coupon_id' => $coupon_id, 'c.goods_id' => $goods_id])
            ->order('end_time', 'asc')
            ->find();

        $discount_amount = 0;
        if (!empty($coupon) && strtotime($coupon['end_time']) < time()) {
            switch ($coupon['coupon_type']) {
                case 1:
                    $discount_amount = $coupon['with_amount'] < $total_amount ? $coupon['used_amount'] : $discount_amount;
                    break;
                case 2:
                    $discount_amount = $coupon['used_amount'];
                    break;
            }
            Db::name('user_coupon')->where('id', $coupon['id'])->update(['status' => 2]);
        }

        return $discount_amount;
    }

    /**
     * 修改订单状态
     * */
    public static function changeOrder($out_trade_no, $time)
    {
        $order = Db::name('order_trade')
            ->alias('a')
            ->field('a.order_id,b.user_id,b.order_type,b.redeem_integral,a.trade_fee')
            ->join('order b', 'a.order_id=b.id')
            ->where('a.out_trade_no', $out_trade_no)
            ->find();

        Db::name('order_trade')
            ->where('out_trade_no', $out_trade_no)
            ->update([
                'trade_status' => 1,
                'trade_time' => $time,
            ]);

        Db::name('order')->where('id', $order['order_id'])->update([
            'status' => 2,
        ]);
    }

    /**
     * 购物车下单
     */
    public static function saveCartOrder($data, $item)
    {
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId([
                'user_id' => $data['user_id'],
                'store_id' => $data['store_id'],
                'order_type' => $data['order_type'],
                'order_no' => $data['order_no'],
                'logistics_mode' => empty($data['logistics_mode']) ? '' : $data['logistics_mode'],
                'pick_point_id' => empty($data['pick_point_id']) ? '' : $data['pick_point_id'],
                'grade_discount_amount' => empty($data['grade_discount_amount']) ? 0 : $data['grade_discount_amount'],
                'discount_amount' => isset($data['discount_amount']) ? $data['discount_amount'] : 0,
                'real_amount' => $data['real_amount'],
                'redeem_integral' => isset($data['redeem_integral']) ? $data['redeem_integral'] : 0,
                'give_integral' => isset($data['give_integral']) ? $data['give_integral'] : 0,
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'status' => 1,
                'create_time' => time(),
                'expire_time' => strtotime('+10 minute'),
            ]);

           

            if (!empty($data['logistics_mode']) && $data['logistics_mode'] == 2) {
                $is_pick_point = Db::name('pick_point')->where(['store_id' => $data['store_id'], 'status' => 1, 'id' => $data['pick_point_id'], 'delete_time' => 0])->find();
                Db::name('order_address')->insert([
                    'order_id' => $order_id,
                    'receiver_name' => $is_pick_point['contact_name'],
                    'receiver_phone' => $is_pick_point['contact_phone'],
                    'province' => $is_pick_point['province'],
                    'city' => $is_pick_point['city'],
                    'county' => $is_pick_point['area'],
                    'address' => $is_pick_point['address'],
                    'lat' => $is_pick_point['lat'],
                    'lng' => $is_pick_point['lng'],
                    'pick_name' => $is_pick_point['name'],
                ]);
            } else {
                Db::name('order_address')->insert([
                    'order_id' => $order_id,
                    'receiver_name' => $data['receiver_name'],
                    'receiver_phone' => $data['receiver_phone'],
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'county' => $data['county'],
                    'address' => $data['address'],
                ]);
            }

            Db::name('order_trade')->insert([
                'store_id' => $data['store_id'],
                'order_id' => $order_id,
                'trade_method' => $data['payment_type'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_fee' => $data['real_amount'],
                'trade_status' => -1,
            ]);

            foreach ($item as $k => $v) {
                Db::name('order_item')->insert([
                    'order_id' => $order_id,
                    'sku_id' => empty($v['sku_id'])?0:$v['sku_id'],
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $v['goods_name'],
                    'attr' => isset($v['attr']) ? $v['attr'] : '',
                    'image' => $v['image'],
                    'market_price' => $v['market_price'],
                    'sell_price' => $v['sell_price'],
                    'buy_num' => $v['buy_num'],
                    'total_amount' => isset($v['goods_total_amount']) ? $v['goods_total_amount'] : $v['goods_total_amount'],
                    'redeem_integral' =>0,
                ]);
                 //减库存
                if (!empty($v['sku_id'])) {
                    //减规格的库存
                    Db::name('goods_item')->where('id', $v['sku_id'])->dec('stock', $v['buy_num'])->update();
                } else {
                    Db::name('goods')->where('id', $v['goods_id'])->dec('stock', $v['buy_num'])->update();
                }
                Db::name('cart')->where('id', $v['cid'])->update(['delete_time'=>time()]);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();exit;
            return false;
        }
    }

    /**
     * 保存订单信息
     *
     * */
    public static function saveOrder($data, $is_free = false, $is_combo = false)
    {
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId([
                'user_id' => $data['user_id'],
                'store_id' => $data['store_id'],
                'order_type' => $data['order_type'],
                'order_no' => $data['order_no'],
                'logistics_mode' => empty($data['logistics_mode']) ? '' : $data['logistics_mode'],
                'pick_point_id' => empty($data['pick_point_id']) ? '' : $data['pick_point_id'],
                'grade_discount_amount' => empty($data['grade_discount_amount']) ? 0 : $data['grade_discount_amount'],
                'discount_amount' => isset($data['discount_amount']) ? $data['discount_amount'] : 0,
                'real_amount' => $data['real_amount'],
                'redeem_integral' => isset($data['redeem_integral']) ? $data['redeem_integral'] : 0,
                'give_integral' => isset($data['give_integral']) ? $data['give_integral'] : 0,
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'status' => 1,
                'create_time' => time(),
                'expire_time' => strtotime('+10 minute'),
            ]);

            //减库存
            if (!empty($data['sku_id'])) {
                //减规格的库存
                Db::name('goods_item')->where('id', $data['sku_id'])->dec('stock', $data['buy_num'])->update();
            } else {
                Db::name('goods')->where('id', $data['goods_id'])->dec('stock', $data['buy_num'])->update();
            }

            if ($is_combo != false) {
                if (!empty($data['logistics_mode']) && $data['logistics_mode'] == 2) {
                    $is_pick_point = Db::name('pick_point')->where(['store_id' => $data['store_id'], 'status' => 1, 'id' => $data['pick_point_id'], 'delete_time' => 0])->find();
                    Db::name('order_address')->insert([
                        'order_id' => $order_id,
                        'receiver_name' => $is_pick_point['contact_name'],
                        'receiver_phone' => $is_pick_point['contact_phone'],
                        'province' => $is_pick_point['province'],
                        'city' => $is_pick_point['city'],
                        'county' => $is_pick_point['area'],
                        'address' => $is_pick_point['address'],
                        'lat' => $is_pick_point['lat'],
                        'lng' => $is_pick_point['lng'],
                        'pick_name' => $is_pick_point['name'],
                    ]);
                } else {
                    Db::name('order_address')->insert([
                        'order_id' => $order_id,
                        'receiver_name' => $data['receiver_name'],
                        'receiver_phone' => $data['receiver_phone'],
                        'province' => $data['province'],
                        'city' => $data['city'],
                        'county' => $data['county'],
                        'address' => $data['address'],
                    ]);
                }
            }

            Db::name('order_trade')->insert([
                'store_id' => $data['store_id'],
                'order_id' => $order_id,
                'trade_method' => $data['payment_type'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_fee' => $data['real_amount'],
                'trade_status' => -1,
            ]);

            Db::name('order_item')->insert([
                'order_id' => $order_id,
                'sku_id' => empty($data['sku_id']) ? '' : $data['sku_id'],
                'goods_id' => $data['goods_id'],
                'goods_name' => $data['goods_name'],
                'attr' => isset($data['attr']) ? $data['attr'] : '',
                'image' => $data['image'],
                'market_price' => $data['market_price'],
                'sell_price' => $data['sell_price'],
                'buy_num' => $data['buy_num'],
                'total_amount' => isset($data['total_amount']) ? $data['total_amount'] : $data['real_amount'],
                'redeem_integral' => isset($data['redeem_integral']) ? $data['redeem_integral'] : 0,
            ]);

            if ($is_free) {
                Db::name('user_task')->insert([
                    'user_id' => $data['user_id'],
                    'task_type' => 6,
                    'join_num' => $data['invite_friend_num'],
                    'start_time' => time(),
                    'end_time' => time() + (int) $data['free_expire_time'] * 3600,
                    'task_status' => 1,
                    'order_id' => $order_id,
                ]);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            // echo $e->getMessage();exit;
            return false;
        }

    }

    /**
     * 获取单规格商品信息
     * */
    public static function findSingleGoods($goods_id)
    {
        $goods = Db::name('goods')
            ->field('id as goods_id,goods_name,spec_type,main_image,market_price,subsidy_price,sell_price,is_subsidy,
                    is_give_integral,stock,is_limit_member,restricted_members,is_free_task,invite_friend_num,free_expire_time')
            ->where(['id' => $goods_id, 'status' => 1])
            ->find();

        return $goods;
    }

    /**
     * 获取多规格商品信息
     * */
    public static function findManyGoods($sku_id, $goods_id)
    {
        $goods = Db::name('goods_item')
            ->field('a.goods_id,b.goods_name,b.main_image,b.spec_type,b.is_subsidy,b.is_give_integral,b.is_limit_member,
                    b.restricted_members,a.attr,a.image,a.market_price,a.sell_price,a.subsidy_price,a.stock,b.is_free_task,
                    b.invite_friend_num,b.free_expire_time')
            ->alias('a')
            ->join('goods b', 'a.goods_id=b.id')
            ->where(['a.id' => $sku_id, 'b.status' => 1, 'b.id'=>$goods_id])
            ->find();

        return $goods;
    }

    /**
     * 获取单规格积分商品信息
     * */
    public static function findSingleSpikeGoods($goods_id, $spike_session_id)
    {
        $goods = Db::name('goods')
            ->alias('a')
            ->field('b.goods_id,a.goods_name,a.spec_type,a.main_image,a.sell_price,b.spike_stock,b.spike_price,d.end_time')
            ->join('spike_goods b', 'b.goods_id=a.id')
            ->join('spike_session_goods c', 'b.id=c.spike_goods_id')
            ->join('spike_session d', 'c.spike_session_id=d.id')
            ->where(['b.id' => $goods_id, 'b.status' => 1, 'c.spike_session_id' => $spike_session_id])
            ->find();

        return $goods;
    }

    /**
     * 获取多规格商品信息
     * */
    public static function findManySpikeGoods($sku_id, $spike_session_id)
    {
        $goods = Db::name('goods_item')
            ->field('a.goods_id,a.attr,a.image,a.sell_price,b.goods_name,b.main_image,b.spec_type,c.spike_price,c.spike_stock,g.end_time')
            ->alias('a')
            ->join('goods b', 'a.goods_id=b.id')
            ->join('spike_goods_item c', 'a.id=c.sku_id')
            ->join('spike_goods d', 'd.id=c.spike_goods_id')
            ->join('spike_session_goods f', 'd.id=f.spike_goods_id')
            ->join('spike_session g', 'f.spike_session_id=g.id')
            ->where(['c.id' => $sku_id, 'd.status' => 1, 'f.spike_session_id' => $spike_session_id])
            ->find();

        return $goods;
    }

    /**
     * 获取订单详情
     * */
    public static function findOrder($order_id)
    {
        $order = Order::withoutField('store_id,user_id')
            ->where('id', $order_id)
            ->with(['items', 'address', 'trade'])->find();

        return $order;
    }

    /**
     * 发起退款
     * */

    public static function sponsorRefund($param)
    {
        Db::startTrans();
        try {
            Db::name('order')->where('order_id', $param['order_id'])->update(['is_after_sale' => 1]);
            Db::name('order_trade')->where('order_id', $param['order_id'])
                ->update([
                    'refund_status' => 1,
                    'refund_reason' => $param['refund_reason'],
                ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

}
